package com.application.adminapi;

import com.application.common.utils.VerifyKit;
import com.application.model.Global;
import com.application.model.Order;
import com.application.module.couponget.CouponGet;
import com.application.module.userinfo.Userinfo;
import com.application.module.userinfo.UserinfoValidator;
import com.application.module.usermoney.ChargeUserMoney;
import com.application.validate.AdminValidator;
import com.application.validate.UserBackendValidator;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.user.User;
import com.platform.mvc.user.UserValidator;
import com.platform.tools.ToolCache;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 */
@Controller("/admin-api/user")
public class UserController extends BaseController {

    @SuppressWarnings("unused")
    private static final Log log = Log.getLog(UserController.class);

    private static final String list1 = "app.user2.splitPageSelect";
    private static final String list2 = "app.user2.splitPageFrom";
    private static final String list3 = "app.user2.totalSelect";
    /**
     */
    public void index() {

        /*splitPage.setOrderColunm("create_at");
        splitPage.setOrderMode("desc");*/
        Map<String, Object> param = splitPage.getQueryParam();
        param.put("time1", getPara("create_at[0]"));
        param.put("time2", getPara("create_at[1]"));
        param.put("user", 1);
        param.put("roleid", getPara("role_id"));
        paging(splitPage, list1, list2);
        List<Record> list = (List<Record>) splitPage.getList();
        list.forEach(o -> {
            o.set(User.column_password, "");
            int uid = o.getInt("id");
            int plays = CouponGet.dao.findAvailableNum(uid, CouponGet.TYPE_PLAY);
            Userinfo info = Userinfo.dao.findById(uid);
            o.set("info_plays", plays);
            o.set("info_tips", info == null ? "" : info.get("tips"));
            //上次付费时间
            Order order = Order.dao.findLastOrder(uid);
            o.set("last_paydate", order == null ? null : order.getCreate_time());
        });

        String s = getSqlMy(list3) + getSqlByBeetl(list2, splitPage.getQueryParam());

        splitPage.setExtData(Db.findFirst(s));

        renderOk(splitPage);
    }


    /**
     * 保存新增用户
     */
    @Before({UserValidator.class})
    public void save() {

        String password = getPara("password");
        User user = User.dao.getModelByMap(password, super.getParamMap());
        try {
            //特殊数据类型处理
            User.saveInfo(user);
            Userinfo info = new Userinfo();
            info.set("userid", user.getId()).set("tips", getPara("info_tips")).save();
        } catch (Exception e) {
            e.printStackTrace();
            renderErr(500, "", e.getMessage());
            return;
        }

        renderOk("reload", "保存成功", null);
    }


    /**
     * 更新,修改管理员信息时需校验身份
     */
    @Before(AdminValidator.class)
    public void update() {
        int id = getParaToInt("id");
        Map<String, Object> formMap = new HashMap<>();
        for (String s : getParamMap().keySet()) {
            formMap.put(s, getPara(s));
        }

        String password = getPara("password");
        if(StrKit.notBlank(password)) {
            formMap.put("password", DigestUtils.md5Hex(password));
        }

        boolean f = Db.update(getSqlByBeetl("app.user2.update", formMap)) > 0;

        Userinfo info = Userinfo.dao.findById(id);
        String tips = getPara("info_tips");
        if (info == null) {
            if(StrKit.notBlank(tips)) {
                info = new Userinfo();
                info.set("userid", id).set("tips", tips).save();
            }
        } else {
            info.set("tips", tips).update();
        }
        if (f) {
            User.cacheRemove(String.valueOf(id));
            renderOk("refresh", "修改成功", null);
        } else {
            renderErr(500, "", "修改失败");
        }

    }

    /**
     * 删除
     */
    @Before({AdminValidator.class, UserBackendValidator.class})
    public void delete() {
        User.dao.deleteByIds(getPara() == null ? getPara("id") : getPara());
        renderOk("refresh", "删除成功", null);
    }

    /*
    查询用户信息
     */
    public void view() {
        String userid = getPara() == null ? super.getCUserIds() : getPara();
        User user = User.dao.cacheGetByUserId(userid);
        user.setPassword("");
        if (user.get("referee_userid") != null) {
            User p = User.dao.findById(user.getInt("referee_userid"));
            if (p != null) {
                user.put("referee_name", p.getName() + "(" + p.getUsername() + ")");
            }
        }
        renderOk(user);
    }

    /**
     * 修改用户角色
     * @param id
     * @param roleId
     */
    @Before({AdminValidator.class, UserinfoValidator.class})
    public void changeRole(){
        String rid = getPara("role_id");
        String uid = getPara("id");
        Date date = null;

        if(StrKit.notBlank(getPara("role_date"))) {
            date = getParaToDate("role_date");
        }

        if(StrKit.isBlank(rid) || StrKit.isBlank(uid)){
            renderErr(400, "", "参数为空");
            return;
        }
        User user = User.dao.findById(uid);
        boolean b = user.set("role_id", rid).set("role_date", date).update();

        if(b) {
            User.dao.cacheRemove(uid);
            renderOk("refresh", "修改成功", null);
        } else {
            renderErr(400, "", "修改失败");
        }
    }


    /*
    给用户充值
     */
    @Deprecated
    public void charge() {
        String msg = "充值成功";
        String uid = getPara("id");
        String money = getPara("money");
        String code = getPara("valicode");
        Global g = Global.cacheGetByCode(Global.Code.admin_mobile);

        if (VerifyKit.verify(g.getValue(), code)) {
            //金额校验
            String m = ToolCache.get(g.getValue() + "_extra");
            if (money.equalsIgnoreCase(m)) {
                User u = User.dao.findById(uid);
                u.set("money", u.getBigDecimal("money").add(new BigDecimal(money))).update();
                User.dao.cacheRemove(uid);
                String orderNo = "c" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "0000";
                new ChargeUserMoney().create(u.getId(), m, orderNo, super.getCUserId());
                renderOk("", msg, null);
                return;
            } else {
                msg = "充值金额已改变，请重新输入";
                renderErr(400, "", msg);
                return;
            }
        }
        renderErr(400, "", "充值失败");
    }


    /*
    参数:keyword
    前端传递的keyword为乱码
     */
    public void query() {
        String str = "";
        try {
            str = new String(getPara("keyword").getBytes("iso-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            str = getPara("keyword");
        }
        List<User> list = User.dao.queryByNo(str);
        success(list);
    }
}


